package spring.cloud.tasks.executor.name_space.executor.task.task_listener.task_configuration;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.name_space.executor.task.task_listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.LogUtils;

@Slf4j
@Setter
@Getter
class TaskCronConfigurationUpdateListener extends TreeCacheListener {

    private final TaskConfigurationListenerHolder taskConfigurationListenerHolder;

    public TaskCronConfigurationUpdateListener(TaskConfigurationListenerHolder taskConfigurationListenerHolder) {
        this.taskConfigurationListenerHolder = taskConfigurationListenerHolder;
    }

    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (taskConfigurationListenerHolder.isShutdown) {
            return;
        }
        if (TaskConfigurationNode.isCronPath(taskConfigurationListenerHolder.taskId, path) && TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) {
            LogUtils.info(log, taskConfigurationListenerHolder.taskId, "{} 's cron update", taskConfigurationListenerHolder.taskId);
            String cronExpressionUpdateIdFromZooKeeper = taskConfigurationListenerHolder.taskConfiguration.getCronExpressionUpdateIdFromZooKeeper(); // will update local cron cache
            if (!taskConfigurationListenerHolder.taskExecutor.getPreviousTaskConfiguration().getCronExpressionUpdateId().equals(cronExpressionUpdateIdFromZooKeeper)) {
                taskConfigurationListenerHolder.taskExecutor.getPreviousTaskConfiguration().setCronExpression(taskConfigurationListenerHolder.taskConfiguration.getCronExpression());
                taskConfigurationListenerHolder.taskExecutor.getPreviousTaskConfiguration().setPauseDatePeriod(taskConfigurationListenerHolder.taskConfiguration.getPauseDatePeriodFromZooKeeper());
                taskConfigurationListenerHolder.taskExecutor.getPreviousTaskConfiguration().setPauseTimePeriod(taskConfigurationListenerHolder.taskConfiguration.getPauseTimePeriodFromZooKeeper());
                taskConfigurationListenerHolder.taskExecutor.getPreviousTaskConfiguration().setCronExpressionUpdateId(cronExpressionUpdateIdFromZooKeeper);


            }
        }
    }
}
